package com.qs.rocketmq.mb.utils;

import cn.hutool.core.collection.CollUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StringHandlerUtil {

    public static void main(String[] args) {
        List<String> result = Arrays.asList("1", "3");
        String value = composeBitValue(result, 3);
        System.out.println("==>>" + value);
    }

    public static String composeBitValue(List<String> items, int len) {
        if (CollUtil.isEmpty(items)) {
            return null;
        }

        List<String> bitValues = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            String item = items.get(i);
            int index = Integer.parseInt(item) - 1;
            String itemValue = getBinaryString(index, len);
            bitValues.add(itemValue);
        }

        String bitValue = "0";
        for (String element : bitValues) {
            bitValue = Integer.toBinaryString(Integer.parseInt(element, 2) | Integer.parseInt(bitValue, 2));
        }

        return addZero(bitValue, len);
    }

    private static String addZero(String item, int len) {
        StringBuilder itemValue = new StringBuilder(item);
        if(item.length()<len){
            int cnt = len - item.length();
            while(cnt >0){
                cnt--;
                itemValue.insert(0, 0);
            }
        }

        return itemValue.toString();
    }

    private static String getBinaryString(int index, int len) {
        StringBuilder value = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if(i==index){
                value.append("1");
            }else{
                value.append("0");
            }
        }

        return value.toString();
    }



}
